﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UsefulExtensionMethods
{
    public static class DateTimeExtensions
    {
        public static int ToAge(this DateTime dob)
        {
            DateTime now = DateTime.Now;
            int age = now.Year - dob.Year;
            if (now < dob.AddYears(age)) age--;
            return age;
        }

        public static string ToTimeToComeString(this DateTime date, DateTime future, string suffix)
        {
            TimeSpan diff = date - future;

            if (diff.TotalDays < -1)
                return ((int)diff.TotalDays * -1).ToString() + " days " + suffix;
            else if (diff.TotalHours < -1)
                return ((int)diff.TotalHours * -1).ToString() + " hours " + suffix;
            else if (diff.TotalMinutes < -1)
                return ((int)diff.TotalMinutes * -1).ToString() + " minutes " + suffix;
            else if (diff.TotalSeconds < -1)
                return ((int)diff.TotalSeconds * -1).ToString() + " seconds " + suffix;

            return String.Empty;
        }

        public static string ToTimeAgoString(this DateTime date, string format)
        {
            TimeSpan t = DateTime.Now - date;

            if (t.TotalDays > 9)
                return date.ToString(format);
            else if (t.TotalHours > 24)
            {
                if (t.TotalDays == 1)
                {
                    return "1 day ago";
                }
                else
                {
                    return String.Format("about {0} days ago", t.TotalDays.ToString("0"));
                }
            }
            else if (t.TotalMinutes > 60)
            {
                if (t.TotalHours == 1)
                {
                    return "1 hour ago";
                }
                else
                {
                    return String.Format("about {0} hours ago", t.TotalHours.ToString("0"));
                }
            }
            else if (t.TotalSeconds > 60)
            {
                if (t.TotalMinutes == 1)
                {
                    return "1 minute ago";
                }
                else
                {
                    return String.Format("about {0} minutes ago", t.TotalMinutes.ToString("0"));
                }
            }
            else
            {
                if (t.TotalSeconds == 1)
                {
                    return "1 second ago";
                }
                else
                {
                    return String.Format("about {0} seconds ago", t.TotalSeconds.ToString("0"));
                }
            }
        }
    }
}
